package com.example.room;

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.view.View;

import com.example.room.adapter.StudentRecycleViewAdapter;
import com.example.room.entity.Student;
import com.example.room.viewModel.StudentViewModel;

import java.util.ArrayList;
import java.util.List;

public class StudentAutoActivity extends AppCompatActivity {

    private StudentRecycleViewAdapter adapter;
    private List<Student> list;
    private RecyclerView rv_student;
    private StudentViewModel viewModel;

    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_student_auto_actiity);

        rv_student = findViewById(R.id.rv_student);
        list = new ArrayList<>();
        adapter = new StudentRecycleViewAdapter(list);
        rv_student.setAdapter(adapter);
        rv_student.setLayoutManager(new LinearLayoutManager(this));

        //创建viewModel对象 为queryAll方法添加观察 用于自动查询 只要数据发生变化就更更新
        viewModel = new ViewModelProvider(this, new ViewModelProvider.AndroidViewModelFactory(getApplication())).get(StudentViewModel.class);
        viewModel.queryAll().observe(this, new Observer<List<Student>>() {
            @Override
            public void onChanged(List<Student> students) {
                adapter.setList(students);
                adapter.notifyDataSetChanged();
            }
        });
    }

    public void addStudentInfo(View view) {
        Student s1 = new Student("jack", 20);
        Student s2 = new Student("jason", 20);
        viewModel.insert(s1, s2);
    }

    public void deleteStudentInfo(View view) {
        Student s3 = new Student(5);
        viewModel.delete(s3);
    }

    public void updateStudentInfo(View view) {
        Student s4 = new Student(4 , "jas" , 50);
        viewModel.update(s4);
    }

    public void deleteAllInfo(View view) {
        viewModel.deleteAll();
    }
}